package com.gws.ievent.db.service;

import com.gws.ievent.common.enums.YesOrNoEnum;
import com.gws.ievent.db.dao.EventDao;
import com.gws.ievent.db.disign.observer.event.cancel.EventCancelledObserverListener;
import com.gws.ievent.db.disign.observer.event.creted.EventCreatedObserverListener;
import com.gws.ievent.db.disign.observer.event.deleted.EventDeletedObserverListener;
import com.gws.ievent.db.disign.observer.event.resume.EventResumedObserverListener;
import com.gws.ievent.db.model.EventModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author song
 * @date 2022/10/23 8:27
 */
@Service
public class EventService {

    @Autowired
    private EventDao eventDao;

    @Autowired
    private EventCreatedObserverListener eventCreatedObserverListener;

    @Autowired
    private EventDeletedObserverListener eventDeletedObserverListener;

    @Autowired
    private EventCancelledObserverListener eventCancelledObserverListener;

    @Autowired
    private EventResumedObserverListener eventResumedObserverListener;


    /**
     * 获取未删除的事件
     *
     * @return
     */
    public List<EventModel> getNotDeletedList() {
        return eventDao.query()
                .eq("deleted_at", 0)
                .list();
    }


    /**
     * 添加
     *
     * @param model
     * @return
     */
    public boolean create(EventModel model) {
        boolean save = eventDao.save(model);
        if (save) {
            // 插入时间监听
            eventCreatedObserverListener.notice(model);
        }

        return save;
    }


    /**
     * 取消事件
     *
     * @param id
     * @return
     */
    public boolean cancel(long id) {
        EventModel model = new EventModel();
        model.setId(id);
        model.setCancel(YesOrNoEnum.YES.getValue());
        boolean update = eventDao.updateById(model);
        if (update) {
            eventCancelledObserverListener.notice(model);
        }

        return update;
    }


    /**
     * 恢复件
     *
     * @param id
     * @return
     */
    public boolean resume(long id) {
        EventModel model = new EventModel();
        model.setId(id);
        model.setCancel(YesOrNoEnum.NO.getValue());
        boolean update = eventDao.updateById(model);
        if (update) {
            EventModel byId = eventDao.getById(id);
            // 插入时间监听
            eventResumedObserverListener.notice(byId);
        }

        return update;
    }


    /**
     * 删除事件
     *
     * @param id
     * @return
     */
    public boolean delete(long id) {
        EventModel model = new EventModel();
        model.setId(id);
        model.setDeletedAt(System.currentTimeMillis());
        boolean delete = eventDao.updateById(model);
        if (delete) {
            eventDeletedObserverListener.notice(model);
        }

        return delete;
    }

}
